<template>
  <div class="app-container">
    <!-- 查询区域 -->
    <el-card class="search-card">
      <el-form :model="queryParams">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="仓库名称">
              <el-input v-model="queryParams.warehouseName" placeholder="请输入仓库名称" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="仓库类型">
              <el-select v-model="queryParams.warehouseType" placeholder="请选择仓库类型" clearable>
                <el-option v-for="item in warehouseTypeOptions" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="分区名称">
              <el-input v-model="queryParams.partitionName" placeholder="请输入分区名称" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="4" style="text-align: left;">
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 数据表格区域 -->
    <el-card class="mt-1">
      <el-button type="primary" @click="handleAdd">
        <el-icon>
          <Plus />
        </el-icon>
        新增仓库
      </el-button>
      <el-table :data="warehouseList" border v-loading="loading" @selection-change="handleSelectionChange" class="mt-2">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="warehouseId" label="仓库编号"  align="center" />
        <el-table-column prop="warehouseName" label="仓库名称" align="center" />
        <el-table-column prop="warehouseType" label="仓库类型" align="center">
          <template #default="{ row }">
            {{ getWarehouseTypeLabel(row.warehouseType) }}
          </template>
        </el-table-column>
        <el-table-column prop="locationDetail" label="位置信息" align="center" />
        <el-table-column prop="partitionName" label="分区名称" align="center" />
        <el-table-column prop="equipmentMaterialId" label="存储物料" align="center" >
          <template #default="{ row }">
            <el-tag>
              {{ getName(equipmentMaterialOptions,row.equipmentMaterialId,'id','name') }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="inventoryQuantityInWarehouse" label="库存数量" align="center" />
        <el-table-column label="操作" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">查看</el-button>
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination class="mt-2" background layout="total, sizes, prev, pager, next, jumper" :total="total"
        v-model:page-size="queryParams.pageSize" v-model:current-page="queryParams.pageNum"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="800px" :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="仓库编号" prop="warehouseId">
          <el-input v-model="form.warehouseId" placeholder="请输入仓库编号" />
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehouseName">
          <el-input v-model="form.warehouseName" placeholder="请输入仓库名称" />
        </el-form-item>
        <el-form-item label="仓库类型" prop="warehouseType">
          <el-select v-model="form.warehouseType" placeholder="请选择仓库类型" style="width: 100%">
            <el-option v-for="item in warehouseTypeOptions" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="位置信息" prop="locationDetail">
          <el-input v-model="form.locationDetail" type="textarea" :rows="2" placeholder="请输入详细位置信息" />
        </el-form-item>
        <el-form-item label="仓库面积(m²)" prop="areaSize">
          <el-input-number v-model="form.areaSize" :min="0" :precision="2" controls-position="right"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="存储容量" prop="storageCapacity">
          <el-input-number v-model="form.storageCapacity" :min="0" :precision="0" controls-position="right"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="分区名称" prop="partitionName">
          <el-input v-model="form.partitionName" placeholder="请输入分区名称" />
        </el-form-item>
        <el-form-item label="分区描述" prop="partitionDescription">
          <el-input v-model="form.partitionDescription" type="textarea" :rows="2" placeholder="请输入分区描述" />
        </el-form-item>
        <el-form-item label="存储物料" prop="equipmentMaterialId">
          <el-select v-model="form.equipmentMaterialId" placeholder="请选择存储物料" style="width: 100%">
            <el-option v-for="item in equipmentMaterialOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="库存数量" prop="inventoryQuantityInWarehouse">
          <el-input-number v-model="form.inventoryQuantityInWarehouse" :min="0" :precision="2" controls-position="right"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="存储位置" prop="storageLocationInWarehouse">
          <el-input v-model="form.storageLocationInWarehouse" placeholder="请输入具体存储位置" />
        </el-form-item>
        <el-form-item label="入库时间">
          <el-date-picker v-model="form.inStorageTime" type="datetime" placeholder="选择入库时间"
            value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
        </el-form-item>
        <el-form-item label="出库时间">
          <el-date-picker v-model="form.outStorageTime" type="datetime" placeholder="选择出库时间"
            value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
        </el-form-item>
        <el-form-item label="批次号">
          <el-input v-model="form.batchNumber" placeholder="请输入批次号" />
        </el-form-item>
        <el-form-item label="备注信息">
          <el-input v-model="form.remarks" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialog.visible" :title="`仓库详情 - ${detailDialog.data.warehouseName}`" width="800px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="仓库编号">{{ detailDialog.data.warehouseId }}</el-descriptions-item>
        <el-descriptions-item label="仓库名称">{{ detailDialog.data.warehouseName }}</el-descriptions-item>
        <el-descriptions-item label="仓库类型">{{ getWarehouseTypeLabel(detailDialog.data.warehouseType)
        }}</el-descriptions-item>
        <el-descriptions-item label="位置信息">{{ detailDialog.data.locationDetail }}</el-descriptions-item>
        <el-descriptions-item label="仓库面积">{{ detailDialog.data.areaSize }} m²</el-descriptions-item>
        <el-descriptions-item label="存储容量">{{ detailDialog.data.storageCapacity }}</el-descriptions-item>
        <el-descriptions-item label="分区名称">{{ detailDialog.data.partitionName }}</el-descriptions-item>
        <el-descriptions-item label="分区描述">
          <pre>{{ detailDialog.data.partitionDescription || '无' }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="存储物料">{{ detailDialog.data.equipmentMaterialName }}</el-descriptions-item>
        <el-descriptions-item label="库存数量">{{ detailDialog.data.inventoryQuantityInWarehouse }}</el-descriptions-item>
        <el-descriptions-item label="存储位置">{{ detailDialog.data.storageLocationInWarehouse }}</el-descriptions-item>
        <el-descriptions-item label="入库时间">{{ detailDialog.data.inStorageTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="出库时间">{{ detailDialog.data.outStorageTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="批次号">{{ detailDialog.data.batchNumber || '-' }}</el-descriptions-item>
        <el-descriptions-item label="备注信息">
          <pre>{{ detailDialog.data.remarks || '无' }}</pre>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getEquipmentMaterialList,
  getWarehouseTypeList,
  listWarehouseManagement,
  getWarehouseManagementDetail,
  addWarehouseManagement,
  updateWarehouseManagement,
  deleteWarehouseManagement
} from '@/api/prod_operate/device/warehouse/stash'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  warehouseName: '',
  warehouseType: '',
  partitionName: ''
})

// 表单数据
const form = reactive({
  id: undefined,
  warehouseId: '',
  warehouseName: '',
  warehouseType: '',
  locationDetail: '',
  areaSize: 0,
  storageCapacity: 0,
  partitionName: '',
  partitionDescription: '',
  equipmentMaterialId: '',
  inventoryQuantityInWarehouse: 0,
  storageLocationInWarehouse: '',
  inStorageTime: '',
  outStorageTime: '',
  batchNumber: '',
  remarks: ''
})

// 对话框控制
const dialog = reactive({
  visible: false,
  title: ''
})

const detailDialog = reactive({
  visible: false,
  data: {}
})

// 下拉选项数据
const equipmentMaterialOptions = ref([])
const warehouseTypeOptions = ref([])

// 表格数据
const warehouseList = ref([])
const total = ref(0)
const loading = ref(false)
const selectedRows = ref([])
const formRef = ref()

// 表单验证规则
const rules = reactive({
  warehouseId: [
    { required: true, message: '请输入仓库编号', trigger: 'blur' }
  ],
  warehouseName: [
    { required: true, message: '请输入仓库名称', trigger: 'blur' }
  ],
  warehouseType: [
    { required: true, message: '请选择仓库类型', trigger: 'change' }
  ],
  locationDetail: [
    { required: true, message: '请输入位置信息', trigger: 'blur' }
  ],
  areaSize: [
    { required: true, message: '请输入仓库面积', trigger: 'blur' }
  ],
  storageCapacity: [
    { required: true, message: '请输入存储容量', trigger: 'blur' }
  ],
  equipmentMaterialId: [
    { required: true, message: '请选择存储物料', trigger: 'change' }
  ],
  inventoryQuantityInWarehouse: [
    { required: true, message: '请输入库存数量', trigger: 'blur' }
  ],
  storageLocationInWarehouse: [
    { required: true, message: '请输入存储位置', trigger: 'blur' }
  ]
})

// 获取仓库类型标签
const getWarehouseTypeLabel = (value) => {
  const item = warehouseTypeOptions.value.find(item => item.dictValue === value)
  return item ? item.dictLabel : value
}

// 获取下拉选项数据
const fetchDropdownOptions = async () => {
  try {
    const [materialsRes, typesRes] = await Promise.all([
      getEquipmentMaterialList(),
      getWarehouseTypeList()
    ])

    equipmentMaterialOptions.value = materialsRes.data || []
    warehouseTypeOptions.value = typesRes.data || []

  } catch (error) {
    console.error('获取下拉选项失败:', error)
    ElMessage.error('获取下拉选项失败')
  }
}

// 获取仓库列表
const fetchWarehouseList = async () => {
  try {
    loading.value = true
    const res = await listWarehouseManagement(queryParams)
    warehouseList.value = res.rows || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    ElMessage.error('获取仓库列表失败')
  } finally {
    loading.value = false
  }
}

// 查询按钮
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchWarehouseList()
}

// 重置查询
const resetQuery = () => {
  queryParams.pageNum = 1
  queryParams.warehouseName = ''
  queryParams.warehouseType = ''
  queryParams.partitionName = ''
  fetchWarehouseList()
}

// 分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  fetchWarehouseList()
}

// 当前页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  fetchWarehouseList()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 新增按钮
const handleAdd = () => {
  dialog.visible = true
  dialog.title = '新增仓库'

  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields()
  }

  Object.assign(form, {
    id: undefined,
    warehouseId: '',
    warehouseName: '',
    warehouseType: '',
    locationDetail: '',
    areaSize: 0,
    storageCapacity: 0,
    partitionName: '',
    partitionDescription: '',
    equipmentMaterialId: '',
    inventoryQuantityInWarehouse: 0,
    storageLocationInWarehouse: '',
    inStorageTime: '',
    outStorageTime: '',
    batchNumber: '',
    remarks: ''
  })
}

// 编辑按钮
const handleEdit = async (row) => {
  try {
    const res = await getWarehouseManagementDetail(row.id)
    Object.assign(form, res.data)
    dialog.visible = true
    dialog.title = '编辑仓库'
  } catch (error) {
    console.error('获取仓库详情失败:', error)
    ElMessage.error('获取仓库详情失败')
  }
}

// 查看详情
const handleView = async (row) => {
  try {
    const res = await getWarehouseManagementDetail(row.id)
    detailDialog.data = res.data
    detailDialog.visible = true
  } catch (error) {
    console.error('获取仓库详情失败:', error)
    ElMessage.error('获取仓库详情失败')
  }
}

// 删除按钮
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除仓库 "${row.warehouseName}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return deleteWarehouseManagement(row.id)
  }).then(() => {
    ElMessage.success('删除成功')
    fetchWarehouseList()
  }).catch(() => { })
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()

    const isAdd = form.id === undefined
    const api = isAdd ? addWarehouseManagement : updateWarehouseManagement

    await api(form)
    ElMessage.success('操作成功')
    dialog.visible = false
    fetchWarehouseList()
  } catch (error) {
    console.error('保存仓库信息失败:', error)
  }
}

// 初始化加载数据
onMounted(() => {
  fetchDropdownOptions()
  fetchWarehouseList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mt-2 {
  margin-top: 20px;
}

.pre-formatted {
  white-space: pre-wrap;
  word-wrap: break-word;
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
}
</style>